import 'package:flutter/material.dart';
import 'package:flutter2/colors.dart';
import 'package:flutter2/generated/json/base/json_convert_content.dart';
import 'package:flutter2/http/api.dart';
import 'package:flutter2/http/dio_manager.dart';
import 'package:flutter2/model/sheet_item_entity.dart';
import 'package:flutter2/widget/base/base_container.dart';
import 'package:flutter2/widget/base/normal_text.dart';
import 'package:get/get.dart';
import 'package:flutter2/utils/string.dart';

abstract class SheetItem {
  String getName();
}

class SheetData {
  SheetData._();

  static final Map<String, List<SheetItemEntity>> _map = {};

  static getSheetData({String? type, Function(SheetItemEntity item)? call}) {
    if (type.isNull()) return;
    if (_map[type]?.isNotEmpty == true) {
      var list = _map[type]!;
      showSheetItems<SheetItemEntity>(data: list, call: call);
      return;
    }
    var param = getParams();
    param["videodictionarytyphoon"] = type;
    DioManager.request<Map<String, dynamic>>(
        path: HttpApi.getSheetData,
        onSuccess: (data) {
          if (data == null) return;
          List<SheetItemEntity> list = JsonConvert.fromJsonAsT(data[type]) ?? [];
          _map[type!] = list;
          showSheetItems<SheetItemEntity>(data: list, call: call);
        },
        data: param);
  }

  static showSheetItems<T extends SheetItem>({List<SheetItem>? data, Function(T item)? call}) {
    if (data == null) return;
    showItems(
      data: data.map((e) {
        return e.getName();
      }).toList(),
      call: (item, index) {
        call?.call(data[index] as T);
      },
    );
  }

  static showItems({List<String>? data, Function(String item, int index)? call}) {
    if (data == null || data.isEmpty) return;
    showModalBottomSheet(
      context: Get.overlayContext!,
      builder: (context) {
        return ListView.builder(
          shrinkWrap: true,
          physics: BouncingScrollPhysics(),
          itemCount: data.length,
          itemBuilder: (context, index) {
            return BaseContainer(
              click: () {
                call?.call(data[index], index);
                Get.back(closeOverlays: false);
              },
              width: double.infinity,
              padding: EdgeInsets.only(
                top: index == 0 ? 16 : 8,
                left: 15,
                right: 15,
                bottom: index == data.length - 1 ? 16 : 8,
              ),
              child: NormalText(
                text: data[index],
                fontColor: mainText,
                fontSize: 16,
              ),
            );
          },
        );
      },
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadiusGeometry.vertical(
          top: Radius.circular(10),
        ),
      ),
    );
  }
}
